<template>
  <div v-if="!isLoadOption" class="e_charts">
    <l-echart ref="chartRef" @finished="init"></l-echart>
  </div>
</template>

<script>
import * as echarts from '@/uni_modules/lime-echart/static/echarts.min'
import { cloneDeep } from 'lodash-es'
import { convertRem } from '@/utils/common'
export default {
  props: {
    config: {
      type: Object,
      default: () => {
        return {};
      }
    },
    data: {
      type: Array,
      default: () => {
        return [];
      }
    }
  },
	data() {
		return {
      isLoadOption: false,
      extendsInfo:{},
      curOption: {},
      option: {
        tooltip: {
          show:false,
          trigger: 'axis',
          backgroundColor: '#FBE3C6',
          confine:true,
          axisPointer: {
            type: 'line', //默认为直线，可选为：'line'|'shadow'
          },
          textStyle: {
            fontSize:convertRem(24),
            color: '#BF9D73'
          },
          formatter: params => {
            let content='';
            params.forEach((item,index) => {
              if(index == 0){
                content += item.axisValue + '\n'
              }
              if (typeof item.color !== 'string') {
                item.marker = item.marker.replace('[object Object]', item.color.colorStops[0].color);
              }
              content += item.marker + item.seriesName + ': ' + (item.componentSubType === 'line' ? (item.value * 1 || 0) + ((this.extendsInfo[item.seriesName] || {}).unit || '') : (item.value * 1 || 0)) + (index < params.length - 1 ? '\n' : '');
           });
            return content;
          }
        },
        grid: {
          top: convertRem(120),
          left: convertRem(30),
          right: convertRem(30),
          bottom:convertRem(30),
          containLabel: true
        },
        legend: {
          show:false,
          data: [],
          top: 0,
          left: 'center',
          icon: 'circle',
          textStyle: {
            color: '#FBE3C6'
          },
          itemWidth: convertRem(20),
          itemHeight: convertRem(20),
        },
        xAxis: {
          type: 'category',
          axisLine: {
            show:false,
            lineStyle: {
              color: '#FBE3C6'
            }
          },
          axisTick: {
            show: false
          },
          axisLabel: {
            show: false,
            fontSize:convertRem(24),
            color: '#FBE3C6'
          },
          data: []
        },
        yAxis: {
          name: '',
          nameLocation:'end',
          nameTextStyle:{
            align:'center',
            verticalAlign:'middle',
            color:'#9DA3C7',
            fontSize:convertRem(24),
            lineHeight:convertRem(24),
            height:convertRem(24),
            padding:[convertRem(4),convertRem(4)]
          },
          splitNumber:4,
          type: 'value',
          axisLine: {
            show: false,
            lineStyle: { color: '#FBE3C6' }
          },
          splitLine: {
            show: false,
            lineStyle: {
              color: '#FBE3C6'
            }
          },
          axisTick: {
            show: false
          },
          axisLabel: {
            show: false,
            fontSize:convertRem(24),
            color: '#FBE3C6'
          }
        },
        dataZoom: [
          {
            "show": false,
            "height": 24,
            "xAxisIndex": [0],
            bottom: '0%',
            "start": 0,
            "end": 100,
            handleIcon: 'path://M306.1,413c0,2.2-1.8,4-4,4h-59.8c-2.2,0-4-1.8-4-4V200.8c0-2.2,1.8-4,4-4h59.8c2.2,0,4,1.8,4,4V413z',
            handleSize: '110%',
            handleStyle: {
              color: "#e5e5e5",
            },
            textStyle: {
              color: "#fff"
            },
            borderColor: "#e5e5e5"
          }
        ],
        series: [
          {
            name: '数据1',
            type: 'line',
            smooth:true,
            yAxisIndex: 0,
            symbol: (value, params) => {
              if(params.dataIndex === (this.propData.length - 1)){
                return 'image://'+'/static/images/home/line_dot.png'
              }else{
                return 'none'
              }
            },
            symbolSize:convertRem(20),
            itemStyle: {
              normal: {
                color: {
                  type: 'linear',
                  x: 0,
                  y: 0,
                  x2: 0,
                  y2: 1,
                  colorStops: [
                    {
                      offset: 0,
                      color: '#BF9D73' // 0% 处的颜色
                    },
                    {
                      offset: 1,
                      color: '#BF9D73' // 100% 处的颜色
                    }
                  ],
                  global: false // 缺省为 false
                },
                barBorderRadius: 0
              }
            },
            data: []
          },
          {
            name: '数据2',
            type: 'bar',
            barWidth: convertRem(24),
            itemStyle: {
              normal: {
                color: {
                  type: 'linear',
                  x: 0,
                  y: 0,
                  x2: 0,
                  y2: 1,
                  colorStops: [
                    {
                      offset: 0,
                      color: '#2f8ff3' // 0% 处的颜色
                    },
                    {
                      offset: 1,
                      color: '#2f8ff3' // 100% 处的颜色
                    }
                  ],
                  global: false // 缺省为 false
                },
                barBorderRadius: 0
              }
            },
            data: []
          }
        ]
      }
		};
	},
  computed:{
    propConfig () {
      return this.config
    },
    propData () {
      return this.data
    },
  },
  watch: {
    config: {
      handler () {
        this.initMap();
      },
      deep: true
    },
    data: {
      handler () {
        this.initMap();
      },
      deep: true,
      immediate:true
    }
  },
	// 组件能被调用必须是组件的节点已经被渲染到页面上
	methods: {
		async init() {
			// chart 图表实例不能存在data里
			const chart = await this.$refs.chartRef.init(echarts);
			chart.setOption(this.curOption)
		},
    async initMap () {
      if (this.isLoadOption) {
        return false
      }
      this.isLoadOption = true
      const option = cloneDeep(this.option)
      if (this.propConfig) {
        if (this.propConfig.grid) {
          if (Array.isArray(this.propConfig.grid)) {
            option.grid = this.propConfig.grid
          } else {
            option.grid = Object.assign(option.grid || {}, this.propConfig.grid || {})
          }
        }
        if (this.propConfig.tooltip) {
          option.tooltip = Object.assign(option.tooltip || {}, this.propConfig.tooltip || {})
        }
        if (this.propConfig.series) {
          const series = [];
          if (this.propConfig.legend) {
            option.legend = Object.assign(option.legend || {}, this.propConfig.legend || {});
          }
          option.legend.data = [];
          this.propConfig.series.forEach((item, index) => {
            if(!this.extendsInfo[item.name]){
              this.extendsInfo[item.name]={}
            }
            this.extendsInfo[item.name].unit=item.unit
            if (!option.series[index]) {
              option.series[index] = {}
            }
            option.series[index].label = {
              show: false,
              position: "top",
              distance: 5,
              color: "#333"
            }
            item = Object.assign(option.series[index] || {}, item);
            if (index !== 0) {
              option.series[index].label.show = false
            }
            item.data = [];
            series.push(item);
            option.legend.data.push(item.name);
          });
          option.series = series;
        }
        if (this.propConfig.xAxis) {
          let xAxis = option.xAxis;
          if (Array.isArray(this.propConfig.xAxis)) {
            xAxis = [option.xAxis];
            this.propConfig.xAxis.forEach((item, index) => {
              if (xAxis[index]) {
                xAxis[index] = Object.assign(xAxis[index] || {}, item);
              } else {
                xAxis[index] = item;
              }
              xAxis[index].data = undefined
            });
          } else {
            xAxis = Object.assign(xAxis || {}, this.propConfig.xAxis);
            xAxis.data = undefined
          }
          option.xAxis = xAxis;
        }
        if (this.propConfig.yAxis) {
          let yAxis = option.yAxis;
          //定义y轴最大值、最小值
          // let yAxisMax = 1
          // let yAxisMin = 1
          if (Array.isArray(this.propConfig.yAxis)) {
            yAxis = [option.yAxis];
            this.propConfig.yAxis.forEach((item, index) => {
              if (yAxis[index]) {
                yAxis[index] = Object.assign({},yAxis[index] || {}, item);
              } else {
                yAxis[index] = Object.assign({},yAxis[0] || {}, item);
              }
              yAxis[index].data = undefined
            });
          } else {
            yAxis = Object.assign(option.yAxis || {}, this.propConfig.yAxis);
            yAxis.data = undefined
          }
          option.yAxis = yAxis;
        }
        if (this.propConfig.dataZoom) {
          if (Array.isArray(this.propConfig.dataZoom)) {
            this.propConfig.dataZoom.forEach((item, index) => {
              if (option.dataZoom[index]) {
                option.dataZoom[index] = Object.assign(option.dataZoom[index] || {}, item || {})
                option.dataZoom[0].show = false
              }
            })
            option.dataZoom = (option.dataZoom || []).concat(this.propConfig.dataZoom)
          } else {
            option.dataZoom = Object.assign(option.dataZoom || {}, this.propConfig.dataZoom)
            option.dataZoom.show = false
          }
        }
      }
      if (this.propData && this.propData.length) {
        this.propData.forEach((item) => {
          if (option.xAxis.key) {
            if (!option.xAxis.data) {
              option.xAxis.data = [];
            }
            option.xAxis.data.push(item[option.xAxis.key] || undefined);
          }
          if (option.yAxis) {
            if (Array.isArray(option.yAxis)) {
              option.yAxis.forEach((yItem, yIndex) => {
                if (yItem.key) {
                  if (!option.yAxis[yIndex].data) {
                    option.yAxis[yIndex].data = [];
                  }
                  option.yAxis[yIndex].data.push(item[yItem.key] || undefined);
                }
              })
            } else {
              if (option.yAxis.key) {
                if (!option.yAxis.data) {
                  option.yAxis.data = [];
                }
                option.yAxis.data.push(item[option.yAxis.key] || undefined);
              }
            }
          }

          if (option.series && option.series.length) {
            option.series.forEach(sItem => {
              if (sItem.key) {
                if (!sItem.data) {
                  sItem.data = [];
                }
                sItem.data.push(item[sItem.key] || undefined);
              }
            });
          }
        });
        if (option.yAxis  && Array.isArray(option.yAxis) && option.yAxis.length==2){
          if (option.series && Array.isArray(option.series) && option.series.length==2) {
            const minOrMax={}
            const yMinOrMax={}
            option.series.forEach((item,index)=>{
              minOrMax[index]={
                max:Math.max(1, ...(item.data || [])) || 1,
                min:Math.min(0, ...(item.data || [])) || 0
              }
              yMinOrMax[index]={
                max:1,
                min:0
              }
            })
            if(yMinOrMax[0].min<0 || yMinOrMax[1].min<0){
              let ratio = (minOrMax[0].max - minOrMax[0].min) / (minOrMax[1].max - minOrMax[1].min)
              // ratio=Math.floor(ratio)
              // ratio=1000
              if (minOrMax[0].max < minOrMax[1].max * ratio) {
                yMinOrMax[0].max = minOrMax[1].max * ratio;
                yMinOrMax[1].max = minOrMax[1].max;
              } else {
                yMinOrMax[0].max = minOrMax[0].max;
                yMinOrMax[1].max = minOrMax[0].max / ratio;
              }
              if (minOrMax[0].min < minOrMax[1].min * ratio) {
                yMinOrMax[0].min = minOrMax[0].min;
                yMinOrMax[1].min = minOrMax[0].min / ratio;
              } else {
                yMinOrMax[0].min = minOrMax[1].min * ratio;
                yMinOrMax[1].min = minOrMax[1].min;
              }
              option.yAxis.map((item,index)=>{
                item.max=(yMinOrMax[index].max * 1.2).toFixed(2)
                item.min=(yMinOrMax[index].min * 1.2).toFixed(2)
                return item
              })
            }
          }
        }
      }
      if (this.propData.length > 6) {
        option.dataZoom[0].show = false
        if(option.dataZoom[0].show){
          option.dataZoom[0].start = 0
          option.dataZoom[0].end = (600 / this.propData.length)
          let xKey = option.xAxis.key
          if (!Array.isArray(option.yAxis) && option.yAxis.type === 'category') {
            xKey = option.yAxis.key
          }
          if (xKey) {
            var regPos = /^\d+(\.\d+)?$/; //非负浮点数
            if (regPos.test(this.propData[0][xKey])) {
              option.dataZoom[0].start = ((this.propData.length - 6) * 100 / this.propData.length)
              option.dataZoom[0].end = 100
            }
          }
        }
      } else {
        option.dataZoom[0].show = false
      }
      this.curOption = option
      this.$nextTick(()=>{
        this.isLoadOption = false
      })
    },
	},
}
</script>
<style lang="scss" scoped>
.e_charts {
  width: 100%;
  height: 100%;
  color: #fff;
  .chart{
    width: 100%;
    height: 100%;
  }
}
</style>
